#include <netinet/in.h>
#include <sys/socket.h>
#include <fcntl.h>

#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>

#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>


#include <map>

using namespace std;

#define MAX_LINE 16384

void do_read(evutil_socket_t fd, short events, void *arg);
void do_write(evutil_socket_t fd, short events, void *arg);


map<int, bufferevent*> clients;
map<int, bufferevent*>::iterator curClients;
int c_count = 0;

void readcb(struct bufferevent *bev, void *ctx) {
	struct evbuffer *input, *output;
	char *line;
	size_t n;
	evutil_socket_t recv_fd;
	input = bufferevent_get_input(bev);
	//output = bufferevent_get_output(bev);
	recv_fd = bufferevent_getfd( bev );
	printf("from : %d\n", recv_fd);
	while ((line = evbuffer_readln(input, &n, EVBUFFER_EOL_LF))) {
		for( curClients = clients.begin(); curClients!=clients.end(); ++curClients){
			output = bufferevent_get_output(curClients->second);

			char username_buf[1024];
			sprintf(username_buf, "%d:", recv_fd);

			evbuffer_add(output, username_buf, strlen(username_buf));
			evbuffer_add(output, line, n);
			evbuffer_add(output, "\n", 1);
		}

		free(line);
	}
}

void errorcb(struct bufferevent *bev, short error, void *ctx) {
	evutil_socket_t recv_fd;
	if (error & BEV_EVENT_EOF) {
		/* connection has been closed, do any clean up here */
		recv_fd = bufferevent_getfd( bev );
		clients.erase(clients.find(recv_fd));
		--c_count;
		printf("%dth user disconnected. %d remain\n", recv_fd, c_count);

		/* ... */
	} else if (error & BEV_EVENT_ERROR) {
		/* check errno to see what error occurred */
		/* ... */
	} else if (error & BEV_EVENT_TIMEOUT) {
		/* must be a timeout event handle, handle it */
		recv_fd = bufferevent_getfd( bev );
		clients.erase(clients.find(recv_fd));
		--c_count;
		printf("%dth user timeout. %d remain\n", recv_fd, c_count);
	}
	bufferevent_free(bev);
}

void do_accept(evutil_socket_t listener, short event, void *arg) {
	struct event_base* base = (event_base*)arg;
	struct sockaddr_storage ss;
	socklen_t slen = sizeof(ss);
	int fd = accept(listener, (struct sockaddr*) &ss, &slen);
	if (fd < 0) {
		perror("accept");
	} else if (fd > FD_SETSIZE) {
		close(fd);
	} else {
		struct bufferevent *bev;
		evutil_make_socket_nonblocking(fd);
		bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
		bufferevent_setcb(bev, readcb, NULL, errorcb, NULL);
		bufferevent_setwatermark(bev, EV_READ, 0, MAX_LINE);
		bufferevent_enable(bev, EV_READ | EV_WRITE);
		clients.insert( pair<int, bufferevent*>(fd,bev) );
		c_count++;
		printf("connected %dth, fd : %d\n", c_count, fd );
	}
}

void run(void) {
	//#define evutil_socket_t int
	evutil_socket_t listener;
	struct sockaddr_in sin;
	struct event_base *base;
	struct event *listener_event;

	base = event_base_new();
	if (!base)
		return; /*XXXerr*/

	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = 0;
	sin.sin_port = htons(40713);

	listener = socket(AF_INET, SOCK_STREAM, 0);
	evutil_make_socket_nonblocking(listener);

#ifndef WIN32
	{
		int one = 1;
		setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
	}
#endif

	if (bind(listener, (struct sockaddr*) &sin, sizeof(sin)) < 0) {
		perror("bind");
		return;
	}

	if (listen(listener, 16) < 0) {
		perror("listen");
		return;
	}

	listener_event = event_new(base, listener, EV_READ | EV_PERSIST, do_accept, (void*) base);

	event_add(listener_event, NULL);

	event_base_dispatch(base);
}

int main(int c, char **v) {
	setvbuf(stdout, NULL, _IONBF, 0);

	run();
	return 0;
}

